package com.syqc.videos

import android.view.View
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.syqc.comlib.base.LazyLoadSirFragment
import com.syqc.comlib.callback.EmptyCallback
import com.syqc.comlib.custom.timer.CustomDatePicker
import com.syqc.comlib.custom.timer.DateFormatUtils
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.utils.GsonUtil
import com.syqc.comlib.utils.startActivityTo
import com.syqc.entity.KeyValue
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentCarHistoryVideoBinding
import com.syqc.monitor.databinding.IncludeChooseFastTimeBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.monitor.databinding.IncludeTabChangeBinding
import com.syqc.monitor.ui.newaddcar.KeyValuePopup
import com.syqc.adapter.ChooseTimeAdapter
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.utils.TimeUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/**
 *@Author Jasper
 *@Time   2020/7/22
 *@Desc   车辆 历史视频
 */
class CarHistoryVideoFragment :
    LazyLoadSirFragment<FragmentCarHistoryVideoBinding>(FragmentCarHistoryVideoBinding::inflate) {

    private lateinit var mTureVB: IncludeSelectSureBinding
    private lateinit var mFastVB: IncludeChooseFastTimeBinding
    private lateinit var mTabChangeVB: IncludeTabChangeBinding

    private val mActivityVM by activityViewModels<CarMonitorViewModel>()

    private val mViewModel by viewModels<CarHistoryVideoViewModel>()

    private val mKeyValuePopup by lazy { KeyValuePopup(requireActivity()) }

    override fun initView(view: View) {
        mTureVB = IncludeSelectSureBinding.bind(binding.root)
        mFastVB = IncludeChooseFastTimeBinding.bind(binding.root)
        mTabChangeVB = IncludeTabChangeBinding.bind(binding.root)
        binding.lrvChooseCar.isVisible = false
    }

    override fun initData() {
        mViewModel.init(
            getString(R.string.desc_video_all_pass),
            getString(R.string.desc_video_pass)
        )
        mActivityVM.carId.observe(this) {
            mViewModel.carId = it
        }

        mActivityVM.videos.observe(this) {
            mViewModel.videos = it ?: ""
            if (it.isNullOrEmpty()) {
                loadService.setCallBack(EmptyCallback::class.java) { _, view ->
                    val empty = view.findViewById<TextView>(R.id.tv_empty)
                    empty.text = getString(R.string.desc_choose_not_video_car)
                }
                loadService.showCallback(EmptyCallback::class.java)
            } else {
                loadService.showSuccess()
                initView()
            }
        }
        mActivityVM.carName.observe(this) { mViewModel.carName = it }

        if (mViewModel.carId.isEmpty()) {
            loadService.setCallBack(EmptyCallback::class.java) { context, view ->
                val empty = view.findViewById<TextView>(R.id.tv_empty)
                empty.text = getString(R.string.hint_toast_choose_car)
            }
            loadService.showCallback(EmptyCallback::class.java)
        }
        handleModel()
    }


    private fun initView() {
        binding.lrTvPass.setRightText(mViewModel.videoPassList[mViewModel.tmnPass].value)
        binding.lrTvRes.setRightText(DataUtil.getVideoRes(requireContext())[mViewModel.tmnRes].value)
        binding.lrTvStream.setRightText(DataUtil.getVideoStream(requireContext())[mViewModel.tmnStream].value)
        binding.lrTvStorage.setRightText(DataUtil.getVideoStorage(requireContext())[mViewModel.tmnStorage].value)
        mKeyValuePopup.setCallBack(mPopupCallBack)
    }

    override fun initEvent() {
        mTabChangeVB.rdbVideoTmn.setOnClickListener {
            mViewModel.isTmn = true
            binding.lrTvStream.isVisible = true
            binding.lrTvStorage.isVisible = true
            binding.lrTvRes.isVisible = true
        }
        mTabChangeVB.rdbVideoPlate.setOnClickListener {
            mViewModel.isTmn = false
            binding.lrTvStream.isVisible = false
            binding.lrTvStorage.isVisible = false
            binding.lrTvRes.isVisible = false
        }
        mTureVB.tvSure.setOnClickListener {
            mViewModel.getTmVideosInfo(
                binding.lrvStartTime.getRightText(),
                binding.lrvEndTime.getRightText()
            )
        }
        binding.lrTvPass.setOnClickListener {
            mViewModel.popupType = 0
            mKeyValuePopup.showPopupWindow(
                requireActivity().window.decorView,
                getString(R.string.desc_video_passes),
                mViewModel.videoPassList,
                mViewModel.tmnPass
            )
        }
        binding.lrTvRes.setOnClickListener {
            mViewModel.popupType = 1
            mKeyValuePopup.showPopupWindow(
                requireActivity().window.decorView,
                getString(R.string.desc_video_res_type),
                DataUtil.getVideoRes(requireContext()),
                mViewModel.tmnRes
            )
        }
        binding.lrTvStream.setOnClickListener {
            mViewModel.popupType = 2
            mKeyValuePopup.showPopupWindow(
                requireActivity().window.decorView,
                getString(R.string.desc_video_stream_type),
                DataUtil.getVideoStream(requireContext()),
                mViewModel.tmnStream
            )
        }

        binding.lrTvStorage.setOnClickListener {
            mViewModel.popupType = 3
            mKeyValuePopup.showPopupWindow(
                requireActivity().window.decorView,
                getString(R.string.desc_video_storage_type),
                DataUtil.getVideoStorage(requireContext()),
                mViewModel.tmnStorage
            )
        }

        binding.lrvStartTime.rightClick {
            mViewModel.isStart = true
            mDatePicker.show(binding.lrvStartTime.getRightText())
        }

        binding.lrvEndTime.rightClick {
            mViewModel.isStart = false
            mDatePicker.show(binding.lrvEndTime.getRightText())
        }

    }


    /**
     * 资源设置
     */
    private val mPopupCallBack: KeyValuePopup.CallBack = object : KeyValuePopup.CallBack {
        override fun onBack(entity: KeyValue, index: Int) {
            when (mViewModel.popupType) {
                0 -> {
                    mViewModel.tmnPass = index
                    mViewModel.pass = entity.key
                    binding.lrTvPass.setRightText(entity.value)
                }

                1 -> {
                    mViewModel.tmnRes = index
                    binding.lrTvRes.setRightText(entity.value)
                }

                2 -> {
                    mViewModel.tmnStream = index
                    binding.lrTvStream.setRightText(entity.value)
                }

                3 -> {
                    mViewModel.tmnStorage = index
                    binding.lrTvStorage.setRightText(entity.value)
                }
            }
        }
    }

    private fun handleModel() {
        mViewModel.entitySub.hide().autoDispose(scopeProvider)
            .subscribe {
                startActivityTo<HistoryVideoInfoActivity>(requireActivity()) {
                    putExtra(Keys.INTENT_TITLE, mViewModel.carName)
                    putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                    putExtra("isTmn", mViewModel.isTmn)
                    if (mViewModel.pass == "0")
                        putExtra("passJson", GsonUtil.toJson(mViewModel.videoPassList))
                }
                LiveDataBus.get().with("key_history_video").postValue(it)
            }

        mViewModel.toastObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe(this::toastObserver)

        mFastVB.recyclerWrap.layoutManager = GridLayoutManager(context, 4)
        mFastVB.recyclerWrap.adapter = mAdapter.apply {
            setNewInstance(mViewModel.timeList)
            setOnItemClickListener { adapter, view, position ->
                index = position
                notifyDataSetChanged()
                mViewModel.chooseTime(position)
            }
        }
        mViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            binding.lrvStartTime.setRightText(it)
        }

        mViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            binding.lrvEndTime.setRightText(it)
        }
    }

    //*********************************时间选择相关*****************************************************
    private val mAdapter: ChooseTimeAdapter by lazy { ChooseTimeAdapter() }
    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            requireContext(), callback, TimeUtil.normalDate, mViewModel.nowTimeFormat(), true
        ).apply {
            setCanShowPreciseTime(true)
        }
    }
    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mAdapter.index = -1
            mAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, true)

            if (mViewModel.isStart) {
//                if (mViewModel.isOkStart(time, binding.lrvEndTime.getRightText())) return
                binding.lrvStartTime.setRightText(time)
            } else {
//                if (mViewModel.isTimeOk(binding.lrvStartTime.getRightText(), time)) return
                binding.lrvEndTime.setRightText(time)
            }
            mDatePicker.dismiss()
        }
    }
}